/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package db

import (
	"github.com/astaxie/beego"
	"github.com/gomodule/redigo/redis"
	"github.com/pkg/errors"
	"prim-server/logger"
	"strconv"
	"time"
)

var RedisPool *redis.Pool

func init() {
	logger.Info("Start to connect to redis database.")
	var conn = beego.AppConfig.String("redisHost") + ":" + beego.AppConfig.String("redisPort")
	var password = beego.AppConfig.String("redisPassword")
	var dbNum, err = strconv.Atoi(beego.AppConfig.String("redisDB"))
	if err != nil {
		logger.Error("init redis error: %v", err)
		return
	}
	dialFunc := func() (c redis.Conn, err error) {
		c, err = redis.Dial("tcp", conn)
		if err != nil {
			return nil, err
		}

		if password != "" {
			if _, err := c.Do("AUTH", password); err != nil {
				c.Close()
				return nil, err
			}
		}
		_, selecterr := c.Do("SELECT", dbNum)
		if selecterr != nil {
			c.Close()
			return nil, selecterr
		}
		return
	}
	// initialize a new pool, 每个参数的作用需要详细的差
	RedisPool = &redis.Pool{
		MaxIdle:     30,
		IdleTimeout: 180 * time.Second,
		Dial:        dialFunc,
	}
	logger.Info("redis database connected.")
}

//设置key value
func SetRedisKeyValue(key, value string, expTimeSec int) error {
	var redisPrefix = beego.AppConfig.String("redisPrefix")
	redisConn := RedisPool.Get()
	defer redisConn.Close()
	_, err := redisConn.Do("SET", redisPrefix+key, value)
	if err != nil {
		return errors.New("redis set value error")
	}
	_, err = redisConn.Do("expire", redisPrefix+key, expTimeSec)
	if err != nil {
		return errors.New("redis set value error")
	}
	return nil
}

// 获取指定key的value
func GetRedisValue(key string) (interface{}, error) {
	var redisPrefix = beego.AppConfig.String("redisPrefix")
	redisConn := RedisPool.Get()
	defer redisConn.Close()
	reply, err := redisConn.Do("GET", redisPrefix+key)
	if err != nil {
		return nil, errors.New("redis get value error")
	}
	return reply, nil
}

// 判断指定key的值是否存在
func Exists(key string) (interface{}, error) {
	var redisPrefix = beego.AppConfig.String("redisPrefix")
	redisConn := RedisPool.Get()
	defer redisConn.Close()
	reply, err := redisConn.Do("EXISTS", redisPrefix+key)
	if err != nil {
		return nil, errors.New("redis get value error")
	}
	return reply, nil
}

//删除key值
func DelRedisKeys(keys []string) {
	var redisPrefix = beego.AppConfig.String("redisPrefix")
	redisConn := RedisPool.Get()
	defer redisConn.Close()

	redisConn.Do("MULTI")
	for _, v := range keys {
		redisConn.Do("DEL", redisPrefix+v)
	}
	redisConn.Do("EXEC")
}
